#Author http://www.cnblogs.com/Jame-mei
from interface import explain_interface,connect_interface
from multiprocessing import Process
from threading import Thread




def batch_run(cmd):
    '''
    1.执行batch_run的代码部分，交给相应的interface去处理，并拿到返回值。
    :param cmd:
    :return:
    '''
    cmd_dic,msg=explain_interface.common_batch_interface(cmd)
    print(cmd_dic,msg)

    if not cmd_dic:
        print(msg)
    else:
        for host in msg:
            flag,data=explain_interface.get_host_dic_interface(host)
            t_l=[]
            if flag:
                #t=Process(target=connect_interface.connect_run_interface,args=(data,cmd_dic['-cmd']))
                t=Thread(target=connect_interface.connect_run_interface,args=(data,cmd_dic['-cmd']))
                #用线程速度更快！
                t_l.append(t)
                t.start()

            else:
                print(data)
                break

            for t in t_l:
                t.join()





def batch_scp(cmd):
    '''
    2,执行batch_scp函数部分，交给相应的interface去处理，并拿到返回值。
    :return:
    '''
    cmd_dic, msg = explain_interface.common_batch_interface(cmd)
    print(cmd_dic, msg)

    if not cmd_dic:
        print(msg)
    else:
        for host in msg:
            flag, data = explain_interface.get_host_dic_interface(host)
            t_l = []
            if flag:
                t = Process(target=connect_interface.connect_scp_interface, args=(data, cmd_dic))
                t_l.append(t)
                t.start()

            else:
                print(data)
                break

            for t in t_l:
                t.join()






batch_dic={
    'batch_run':batch_run,
    'batch_scp':batch_scp

}





def run():
    while True:
        cmd = input("please input cmd(q 退出)>>>>>>:").strip()
        if not cmd: continue
        if cmd == "q": break
        cmd_header = cmd.split(' ')[0]
        if cmd_header in batch_dic:
            batch_dic[cmd_header](cmd)
        else:
            print("please try agin ...")